<template>
  <Modal v-model="isShow"
         footer-hide
         @on-cancel="closeEvent"
         :mask-closable="false"
         title="初始化用户密码">
    <Form ref="form" :model="formData" :rules="rules">
      <FormItem label="密码" prop="password">
        <Input size="large" placeholder="请输入登陆密码" type="password" password v-model="formData.password"/>
      </FormItem>
      <FormItem label="重复密码" prop="rePassword">
        <Input size="large" placeholder="请再次输入登陆密码" type="password" password v-model="formData.rePassword"/>
      </FormItem>
      <FormItem>
        <Button @click="submitBtnClick" class="initPasswordBtn" size="large" type="primary">确认</Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script>
import {getCertification, initUserPassword} from "@/api/auth/password";
import {Message} from "view-ui-plus";

export default {
  name: "InitPassword",
  data() {
    return {
      isShow: false,
      formData: {
        password: '',
        rePassword: '',
      },
      rules: {
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {type: 'string', max: 128, message: '密码最多为128个字符', trigger: 'blur'}
        ],
        rePassword: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {type: 'string', max: 128, message: '密码最多为128个字符', trigger: 'blur'},
          {validator: this.rePasswordValidator, trigger: 'blur'}
        ],
      },
      account: '',
      accountType: undefined,
      certification: undefined,
    }
  },
  created() {
    getCertification().then(res => {
      this.certification = res.data
    })
  },
  methods: {
    rePasswordValidator(rule, value, callback) {
      if (this.formData.password != this.formData.rePassword) {
        callback(new Error('两次密码输入不一致'));
      } else {
        callback();
      }
    },
    show(p) {
      this.account = p.account
      this.accountType = p.accountType
      this.isShow = true
    },
    closeEvent() {
      this.formData = {
        password: '',
        rePassword: '',
      }
    },
    submitBtnClick() {
      if (!this.certification) {
        location.reload();
      }
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        initUserPassword(this.certification, {
          account: this.account,
          password: this.formData.password,
          accountType: this.accountType
        }).then(res => {
          Message.success("用户密码初始化成功")
          this.isShow = false
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.initPasswordBtn {
  width: 100%;
  letter-spacing: 10px;
}
</style>
